<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="doctorId">
        <el-select
            v-model="queryParams.doctorId"
            placeholder="请选择医生"
            clearable
            filterable
            @keyup.enter="handleQuery"
            STYLE="width: 150px;"
        >
          <el-option
              v-for="doctor in doctorList"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientId">
        <el-select
            v-model="queryParams.patientId"
            placeholder="请选择患者"
            clearable
            filterable
            @keyup.enter="handleQuery"
            STYLE="width: 150px;"
        >
          <el-option
              v-for="patient in patientList"
              :key="patient.patientId"
              :label="patient.realName"
              :value="patient.patientId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生医嘱" prop="doctorMessage">
        <el-input
          v-model="queryParams.doctorMessage"
          placeholder="请输入医生医嘱"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="住院登记" prop="registrationId" >
        <el-input
          v-model="queryParams.registrationId"
          placeholder="请输入住院登记表"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="治疗时间" prop="cureTime">
        <el-date-picker clearable
          v-model="queryParams.cureTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择治疗时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['masterdocker:cure:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['masterdocker:cure:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['masterdocker:cure:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['masterdocker:cure:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="治疗方案ID" align="center" prop="cureId" />
      <el-table-column label="医生姓名" align="center" prop="tyEmployee.name" />
      <el-table-column label="患者姓名" align="center" prop="tyPatient.realName" />
      <el-table-column label="医嘱内容" align="center" prop="doctorMessage"  />
      <el-table-column label="住院登记号" align="center" prop="tyHospitalizationRegistration.registrationId" />
      <el-table-column label="治疗时间" align="center" prop="cureTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cureTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处方数量" align="center" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ row.tyPrescriptionInfoList?.length || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column type="expand" width="50">
        <template #default="{ row }">
          <el-table
              :data="row.tyPrescriptionInfoList"
              border
              size="small"
              class="prescription-table"
          >
            <el-table-column label="处方类型" prop="prescriptionType" width="120">
              <template #default="{ row }">
                <el-tag :type="getPrescriptionTagType(row.prescriptionType)">
                  {{ getPrescriptionTypeLabel(row.prescriptionType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处方名称" prop="name" />
            <el-table-column label="用药天数" prop="days" width="100" />
            <el-table-column label="总剂量" prop="totalAmount" width="100" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                    type="text"
                    size="small"
                    @click="handlePrescDetail(row.prescriptionInfoId)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['masterdocker:cure:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['masterdocker:cure:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改治疗方案对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cureRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主治医生" prop="doctorId" required>
          <el-select
              v-model="form.doctorId"
              placeholder="请选择医生"
              filterable
              @change="handleDoctorChange"
          >
            <el-option
                v-for="doctor in doctorList"
                :key="doctor.id"
                :label="doctor.name"
                :value="doctor.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="患者选择" prop="patientId" required>
          <el-select
              v-model="form.patientId"
              placeholder="请选择患者"
              filterable
              @change="handlePatientChange"
          >
            <el-option
                v-for="patient in patientList"
                :key="patient.patientId"
                :label="patient.realName"
                :value="patient.patientId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医嘱内容" prop="doctorMessage" required>
          <el-input
              v-model="form.doctorMessage"
              type="textarea"
              :rows="4"
              placeholder="请输入详细的医嘱内容"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="住院登记" prop="registrationId" required>
          <el-select
              v-model="form.registrationId"
              placeholder="请选择住院记录"
              :disabled="!form.patientId"
          >
            <el-option
                v-for="reg in registrationList"
                :key="reg.registrationId"
                :label="`住院号：${reg.registrationId}（入院时间：${reg.admissionTime}）`"
                :value="reg.registrationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="治疗时间" prop="cureTime" required>
          <el-date-picker
              v-model="form.cureTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择治疗日期"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="处方信息" prop="tyPrescriptionInfoList" required>
          <div class="prescription-editor">
            <el-table :data="form.tyPrescriptionInfoList">
              <el-table-column label="类型" width="120">
                <template #default="{ row }">
                  <el-select v-model="row.prescriptionType" placeholder="选择类型">
                    <el-option
                        v-for="dict in prescription_type"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="处方名称">
                <template #default="{ row }">
                  <el-input v-model="row.name" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button @click="removePrescription($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button @click="addPrescription">添加处方</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 处方详情弹窗 -->
    <el-dialog
        v-model="prescriptionDialogVisible"
        title="处方详情"
        width="80%"
        append-to-body
    >
      <div v-loading="detailLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="处方类型">
            <el-tag :type="getPrescriptionTagType(prescriptionDetail.prescriptionType)">
              {{ getPrescriptionTypeLabel(prescriptionDetail.prescriptionType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处方名称">{{ prescriptionDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="用药天数">{{ prescriptionDetail.days }} 天</el-descriptions-item>
          <el-descriptions-item label="总剂量">{{ prescriptionDetail.totalAmount }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">药品明细</el-divider>

        <el-table :data="prescriptionDetail.tyPrescriptionMedicineList" border>
          <el-table-column label="药品名称" prop="tyMedicine.medicineName" width="180" />
          <el-table-column label="药品规格" prop="tyMedicine.medicineSpecification" width="180" />
          <el-table-column label="用法" prop="usageMed" width="120" />
          <el-table-column label="天数" prop="daysMed" width="100" />
          <el-table-column label="数量" prop="medicineNum" width="100" />
          <el-table-column label="单价" prop="medicinePrice" width="100">
            <template #default="{ row }">¥{{ row.medicinePrice }}</template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ (row.medicinePrice * row.medicineNum).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="prescriptionDialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Cure">
import {
  getCure,
  delCure,
  addCure,
  updateCure,
  allCure,
  getTyPrescriptionInfoById,
  allPatient, allDoctor
} from "@/api/masterdocker/cure";
import {listBeinhospital} from  "@/api/nurse/beinhospital"
import {getDicts} from "@/api/system/dict/data"
import {parseTime} from "@/utils/ruoyi.js";
import { getCurrentInstance, ref } from 'vue';


const { proxy } = getCurrentInstance();

const doctorList = ref([]); // 医生列表
const patientList = ref([]); // 患者列表
const registrationList = ref([]); // 住院登记列表

const cureList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const prescription_type = ref([]);

// 处方详情相关状态
const prescriptionDialogVisible = ref(false);
const prescriptionDetail = ref({});
const detailLoading = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    doctorId: null,
    patientId: null,
    doctorMessage: null,
    registrationId: null,
    cureTime: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询治疗方案列表 */
function getList() {
  loading.value = true;
  allCure(queryParams.value).then(response => {
    cureList.value = response.rows;
    total.value = response.total;
    console.log(cureList.value);
    console.log(total.value);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    cureId: null,
    doctorId: null,
    patientId: null,
    doctorMessage: null,
    registrationId: null,
    cureTime: null
  };
  proxy.resetForm("cureRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.cureId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加治疗方案";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _cureId = row.cureId || ids.value
  getCure(_cureId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改治疗方案";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cureRef"].validate(valid => {
    if (valid) {
      if (form.value.cureId != null) {
        updateCure(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCure(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cureIds = row.cureId || ids.value;
  proxy.$modal.confirm('是否确认删除治疗方案编号为"' + _cureIds + '"的数据项？').then(function() {
    return delCure(_cureIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('masterdocker/cure/export', {
    ...queryParams.value
  }, `cure_${new Date().getTime()}.xlsx`)
}



// 获取字典数据
getDicts('prescription_type').then(response => {
  prescription_type.value = response.data;
  console.log(prescription_type.value);
});

const getPrescriptionTypeLabel = (type) => {
  // 在字典数组中查找对应的 dictLabel
  const dictItem = prescription_type.value.find(item => item.dictValue === type);
  return dictItem ? dictItem.dictLabel : '未知类型';
};

const getPrescriptionTagType = (type) => {
  const dictItem = prescription_type.value.find(item => item.dictValue === type);
  return dictItem && dictItem.default === 'Y' ? 'success' : 'info';
};


// 查看处方详情
const handlePrescDetail = async (id) => {
  try {
    detailLoading.value = true;
    const res = await getTyPrescriptionInfoById(id);
    if (res.code === 200) {
      prescriptionDetail.value = res.data[0]; // 根据接口返回结构调整
      prescriptionDialogVisible.value = true;
    }
  } catch (error) {
    proxy.$modal.msgError("获取处方详情失败");
  } finally {
    detailLoading.value = false;
  }
};


onMounted(() => {
  getDicts();
  loadDoctors();
  loadPatients();
});


// 加载医生数据
const loadDoctors = async () => {
  const res = await allDoctor();
  doctorList.value = res.data;
};

// 加载患者数据
const loadPatients = async () => {
  const res = await allPatient();
  console.log(res)
  patientList.value = res.data;
};

// 当患者变化时加载住院记录
const handlePatientChange = async (patientId) => {
  if (patientId) {
    const res = await listBeinhospital({ patientId });
    registrationList.value = res.rows;
    console.log(registrationList.value)
  } else {
    registrationList.value = [];
  }
};

// 添加处方操作方法
const addPrescription = () => {
  form.value.tyPrescriptionInfoList.push({
    prescriptionInfoId: null,
    prescriptionType: '',
    name: '',
    days: 1,
    totalAmount: 0,
    tyPrescriptionMedicineList: []
  });
};

const removePrescription = (index) => {
  form.value.tyPrescriptionInfoList.splice(index, 1);
};


getList();
</script>
